package com.ittao.taoaiagent.demo.invoke;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

/**
 * 法二：
 * 发送 HTTP 请求
 */
public class HttpAiInvoke {
    public static void main(String[] args) {
        // 从环境变量或配置中获取 API Key（这里假设 TestAPIKey 是一个你已定义的类）
        String apiKey = TestAPIKey.API_KEY;
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

        // 使用 Hutool 的 JSON 工具构建请求体
        JSONObject systemMessage = new JSONObject()
                .set("role", "system")
                .set("content", "You are a helpful assistant.");

        JSONObject userMessage = new JSONObject()
                .set("role", "user")
                .set("content", "你是谁？");

        JSONArray messages = new JSONArray()
                .set(systemMessage)
                .set(userMessage);

        JSONObject input = new JSONObject()
                .set("messages", messages);

        JSONObject parameters = new JSONObject()
                .set("result_format", "message");

        JSONObject requestBody = new JSONObject()
                .set("model", "qwen-plus")
                .set("input", input)
                .set("parameters", parameters);

        // 发送请求并处理响应
        HttpResponse response = HttpRequest.post(url)
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .execute();

        // 输出结果
        System.out.println("Status Code: " + response.getStatus());
        System.out.println("Response Body: " + response.body());
    }
}